import sysConfigService, { type PageListReq } from "@/api/services/system/configService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { t } from "@/locales/i18n";
import { Button, Card, Drawer, Form, Input, Space, Tabs } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { SysConfig } from "./entity";

const { TextArea } = Input;

export default function SysConfigPage() {
	const [loading, setLoading] = useState(false);
	const [activeType, setActiveType] = useState<string>("system");
	const [queryParams, setQueryParams] = useState<PageListReq>({
		configName: undefined,
		configKey: undefined,
		configType: activeType,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<SysConfig[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<SysConfig | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	// 定义 tab 项
	const tabItems = [
		{ key: "system", label: "系统配置" },
		{ key: "base", label: "基础数据" },
		{ key: "wms", label: "仓库管理" },
		{ key: "mes", label: "生产管理" },
		{ key: "qms", label: "质量管理" },
    { key: "eam", label: "设备管理" },
	];

	// 处理 tab 切换
	const handleTabChange = (key: string) => {
		setActiveType(key);
		setQueryParams((prev) => ({
			...prev,
			configType: key,
			page: 1,
		}));
	};

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<SysConfig> = [
		{
			title: "参数名称",
			width: 120,
			key: "configName",
			dataIndex: "configName",
		},
		{
			title: "参数键名",
			width: 120,
			key: "configKey",
			dataIndex: "configKey",
		},
		{
			title: "参数键值",
			width: 120,
			key: "configValue",
			dataIndex: "configValue",
		},
		{
			title: "参数类型",
			width: 120,
			key: "configType",
			dataIndex: "configType",
		},
		{
			title: "创建时间",
			width: 120,
			key: "createTime",
			dataIndex: "createTime",
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		sysConfigService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (sysConfig: SysConfig) => {
		setEditingData(sysConfig);
		form.setFieldsValue(sysConfig);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (sysConfig: SysConfig) => {
		setEditingData(sysConfig);
		form.setFieldsValue(sysConfig);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingData) {
				await sysConfigService.update({ ...values,configType: activeType, id: editingData.id });
				toast.success("更新参数配置成功");
			} else {
				await sysConfigService.add({...values, configType: activeType});
				toast.success("创建参数配置成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await sysConfigService.remove(selectedRowKeys);
			toast.success("删除参数配置成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			{" "}
			<div className="flex">
				<Tabs
					tabPosition="left"
					activeKey={activeType}
					onChange={handleTabChange}
					items={tabItems}
					className="w-32 border-r border-dashed border-border"
				/>
				<div style={{width: "88%"}}>
					<Card className="mb-4">
						<Form
							layout="inline"
							onFinish={(values) => {
								setQueryParams((prev) => ({
									...prev,
									...values,
									page: 1,
								}));
							}}
						>
							<Form.Item name="configName" label="参数名称">
								<Input placeholder="请输入参数名称" allowClear />
							</Form.Item>
							<Form.Item name="configKey" label="参数键名">
								<Input placeholder="请输入参数键名" allowClear />
							</Form.Item>
							<Form.Item>
								<Button type="primary" htmlType="submit">
									查询
								</Button>
								<Button
									className="ml-2"
									onClick={() => {
										setQueryParams({ page: 1, pageSize: 10 });
									}}
								>
									重置
								</Button>
							</Form.Item>
						</Form>
					</Card>
					<div className="h-4" />
					<Card>
						<div className="flex justify-between mb-4">
							<div className="flex gap-2">
								<Button type="primary" onClick={handleAdd}>
									新增
								</Button>
								<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
									删除
								</Button>
							</div>
							<TableToolbar
								onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
								onSizeChange={setTableSize}
								columns={columns}
								selectedValues={selectedValues}
								onColumnChange={setSelectedValues}
							/>
						</div>
						<Table
							rowKey="id"
							size={tableSize}
							scroll={{ x: "max-content", y: tableScrollY }}
							loading={loading}
							pagination={{
								total,
								current: queryParams.page,
								pageSize: queryParams.pageSize,
								onChange: handlePageChange,
							}}
							columns={filteredColumns}
							dataSource={list}
							rowSelection={{
								type: "checkbox",
								selectedRowKeys: selectedRowKeys,
								onChange: (selectedKeys) => {
									setSelectedRowKeys(selectedKeys as string[]);
								},
							}}
						/>
					</Card>
				</div>
			</div>
			<Drawer
				title={editingData ? "编辑参数配置" : "新增参数配置"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item
						name="configName"
						label="参数名称"
						rules={[
							{
								required: true,
								message: "请填写参数名称",
							},
						]}
					>
						<Input placeholder="请输入参数名称" allowClear />
					</Form.Item>
					<Form.Item
						name="configKey"
						label="参数键名"
						rules={[
							{
								required: true,
								message: "请填写参数键名",
							},
						]}
					>
						<Input placeholder="请输入参数键名" allowClear />
					</Form.Item>
					<Form.Item name="configValue" label="参数键值">
						<Input />
					</Form.Item>
					<Form.Item name="remark" label="备注">
						<TextArea rows={5} />
					</Form.Item>
				</Form>
			</Drawer>
		</>
	);
}
